<template>
 
  <div class="register-page">
    <GhNavBar title="注册" rightText="登录" @click-right="clickRight" />
    <transition name="slide">
    <div class="register-page">
        <!-- <h2>短信验证码注册</h2> -->
        <van-form @submit="submitForm" ref="userFormData">
           <!-- 显示默认图片 -->
           <div class="avatar" >
          <van-uploader  :before-read="beforeRead" :after-read="afterRead" label="头像" accept="image/*" :preview-image="true" mini :max-size="10240*1024"   @oversize="onOversize">
            <img id="avatarImg"  :src="avatarInfo.avatarUrl? avatarInfo.avatarUrl:avatarUrl" >
            <div class="chooseImage">点击选择头像</div>
        </van-uploader>
        </div>
          <van-field  v-model="userForm.username" label="用户名" :rules="userFormRules.username" required label-width="60px" autocomplete="off"></van-field>
          <van-field v-model="userForm.account"  label="手机号" :rules="userFormRules.account" required label-width="60px" autocomplete="off"></van-field>
          <div class="ident-code">
            <van-field class="center-label" v-model="userForm.code"
          name="code" label='验证码' :rules="userFormRules.code" placeholder="请输入验证码" label-width="60px" autocomplete="off" required >
          <!-- <i slot="left-icon" class="gh-ident-code"></i>
          <template #button>
            <van-button class="sendcode-btn" round size="small" type="default">发送验证码</van-button>
          </template> -->
         </van-field>
         <van-button  class="sendcode-btn" round size="small" :disabled="countdown>0" @click="sendIdentCode" :loading="isCountingDown" type="primary">{{ countdown >0 ? `${countdown}s` : '发送验证码' }}</van-button>
          </div>
          
          <van-field  v-model="userForm.password"  label="密码" :rules="userFormRules.password" type="password" placeholder="至少一个字母、一个数字和一个字符" required label-width="60px" autocomplete="off"></van-field>
          <van-field  v-model="userForm.email"  label="邮箱" :rules="userFormRules.email" type="email" required label-width="60px"></van-field>
          <van-field  v-model="userForm.gender" name="radio" label="性别" required label-width="60px">
                <template #input>
                  <van-radio-group v-model="userForm.gender" direction="horizontal" >
                    <van-radio name="男">男</van-radio>
                    <van-radio name="女">女</van-radio>
                  </van-radio-group>
                </template>
           </van-field>          
          <div class="gh-cell">
            <van-button type="primary" native-type="submit" :loading="isRegistering" :disabled="isRegistering" block round>
                注册
              </van-button>
          </div>
        </van-form>
      </div>
    </transition>

  </div>

</template>

<script setup>
import {ref,reactive,computed,onMounted,watchEffect,nextTick,onUnmounted} from "vue"
import{useRouter}from 'vue-router'
const router =useRouter();  
import { Toast, Dialog } from 'vant';
import axios from 'axios'
import 'vant/es/toast/style'


//表单对象
const userForm=ref({
    username:'',
    account:'',
    code:'',
    password:'',
    email:'',
    gender:'男'
})

//定义手机号和验证码的验证规则
const usernameRule=ref([{
    required:true,
    message:'用户名不能为空'
}])
const accountRule =ref([{
          required: true,
          message: '手机号不能为空'
        }, {
          pattern: /^1[3|5|7|8]\d{9}$/,
          message: '手机号格式错误'
        }],)
const codeRule =ref([{
          required: true,
          message: '验证码不能为空'
        }, {
          pattern: /^\d{6}$/,
          message: '验证码格式错误'
        }])
const emailRule=ref([{
    required:true,
    message:'邮箱不能为空'
},{
    pattern:/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/,
    message:'邮箱格式错误'
}])
const passwordRule=ref([{
    required:true,
    message:'密码不能为空'
},
{
    pattern:/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
    message:'密码格式错误'
}])
// 将验证规则对象暴露给模板
const userFormRules = computed(() => {
  return {
    account: accountRule.value,
    code: codeRule.value,
    username:usernameRule.value,
    email:emailRule.value,
    password:passwordRule.value
  };
});

//发送手机验证码
const countdown = ref(0);
const isCountingDown =ref(false)
const sendIdentCode = async() => {
  if(!userForm.value.account){
    Toast('请先输入手机号码')
    return
  }
    if (countdown.value !== 0) {
    return;
  }
  // 发送验证码的逻辑
  try {
    isCountingDown.value = true;
    await new Promise(resolve => {
      axios.post('http://localhost:8888/users/getIdentCode', { account: userForm.value.account },{
    headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization'
  }
})
        .then((res) => {
          Toast('验证码已发送');
         console.log(res.data)
          resolve();
        })
        .catch(error => {
            if(error.response.status=429){
                const toastMessage=error.response.data.error;
                Toast(toastMessage)
                isCountingDown.value = false;
                return
            }
          resolve();
        });
    });
  } finally {
    isCountingDown.value = false;
  }
  countdown.value = 60;
  
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value === 0) {
      clearInterval(timer);
    }
  }, 1000);
};

//引入压缩插件
import ImageCompressor from 'image-compressor.js'

//默认头像地址
const avatarUrl=ref('src/assets/avatar/3.jpg')
//定义图片存储对象
const avatarInfo=ref({
    avatarUrl:''
})



//定义上传的图片图片情况
const uploadfile=ref({
    type:'',
    name:''
})
//图片响应式引用
// const fileList = ref([]);
//压缩图片函数
const compressImage=async(file)=> {
  return new Promise((resolve, reject) => {
         const compressor = new ImageCompressor();

         const options = {
           maxSizeMB: 2,
           maxWidthOrHeight: 1024,
           mimeType: 'image/jpeg',
         };

         compressor.compress(file, options)
           .then((compressedFile) => {
             const reader = new FileReader();
             reader.onloadend = () => {
               resolve(reader.result);
             };
             reader.onerror = (error) => {
               reject(error);
             };
             reader.readAsDataURL(compressedFile);
           })
           .catch((error) => {
             reject(error);
          });
      });
}

//对图片进行压缩的函数
// const compressImage = (file, maxSize) => {
//   return new Promise((resolve, reject) => {
//     const reader = new FileReader();
//     reader.onload = (event) => {
//       const img = new Image();
//       img.src = event.target.result;
//       img.onload = () => {
//         const canvas = document.createElement('canvas');
//         let width = img.width;
//         let height = img.height;
//         let scale = 1;

//         // 根据图片大小进行压缩
//         if (file.size > maxSize) {
//           scale = Math.min(Math.sqrt(maxSize / file.size), 1);
//           width = width * scale;
//           height = height * scale;
//         }

//         // 设置canvas的尺寸，绘制压缩后的图片
//         canvas.width = width;
//         canvas.height = height;
//         const ctx = canvas.getContext('2d');
//         ctx.drawImage(img, 0, 0, width, height);

//         // 将canvas转换为Blob形式的文件
//         canvas.toBlob((blob) => {
//           resolve(blob);
//         }, file.type, 0.8); // 这里可以调整图片的压缩质量，0.8表示80%质量
//       };
//     };
//     reader.readAsDataURL(file);
//   });
// };

//图片上传前的函数
const beforeRead=(file)=>{
    //验证图片格式是否正确
    let regex = /(.jpg|.jpeg)$/;
      if (!regex.test(file.type)) {
        Toast('图片格式不支持上传');
        return false;
      }else{
       return true
        }
 } 
 //将base64格式转为blob对象，并返回size的大小
// const getBase64FileSize=(base64Data) =>{
//   const byteString = atob(base64Data.split(',')[1]);
//   const Buffer = new ArrayBuffer(byteString.length);
//   const uint8Array = new Uint8Array(Buffer);

//   for (let i = 0; i < byteString.length; i++) {
//     uint8Array[i] = byteString.charCodeAt(i);
//   }

//   const blob = new Blob([uint8Array], { type: 'image/jpeg' });

//   return blob.size;
// }



//图片上传后的函数
const afterRead=async(file)=>{
    //将图片赋值给img标签
   if(file.file.size>2097152){
    try {
        // console.log('压缩前的size大小:',file.file.size)
    console.log('进入压缩')
    const base64Image = await compressImage(file.file);
    avatarInfo.value.avatarUrl=base64Image;
     } catch (error) {
       console.error(error);
      }   
   }else{
    avatarInfo.value.avatarUrl=file.content
    // console.log(avatarInfo.value.avatarUrl)
    console.log("不用压缩")

   }
    
}

const onOversize = () => {
  Dialog.alert({
    title: '图片大小超过限制',
    message: '请上传大小不超过 10MB 的图片'
  });
};



import { getImage} from '../utils/imageToBase64.js'



const isRegistering = ref(false);

//点击注册
const submitForm =  () => {
  isRegistering.value = true;
  
     getImage('src/assets/avatar/3.jpg',(res)=>{
                //res就是最终结果
                handleImageResult(res)
        })
     function handleImageResult(res) {
          const base64Image =ref('')
          base64Image.value=res
          // 这里是你对结果进行处理的逻辑
          const avatar=avatarInfo.value.avatarUrl?avatarInfo.value.avatarUrl:base64Image.value
          // console.log(avatar)
          const formData=new FormData();
    
    //  formData.append('avatar',avatar.value)
          formData.append('username', userForm.value.username);
          formData.append('account', userForm.value.account);
          formData.append('code', userForm.value.code);
          formData.append('password', userForm.value.password);
          formData.append('email', userForm.value.email);
          formData.append('gender', userForm.value.gender);
           formData.append('avatar',avatar);
    //        for (const pair of formData.entries()) {
    //       console.log('注册前的表单数据：',pair[0], pair[1]);
    // }
    
    setTimeout(async() => {
  try {
         await new Promise(resolve => {
           axios.post('http://localhost:8888/users/register', formData,{
         headers: {
         'Access-Control-Allow-Origin': '*',
         'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
         'Access-Control-Allow-Headers': 'Content-Type, Authorization'
       }
         })
        .then((res) => {

          Toast.success('注册成功');
        //  console.log(res.data)
        userForm.value={}
        router.push('/login')
          resolve();
        })
        .catch(error => {
          if(error.response.status=402){
            const errorMessage=error.response.data.message;
            Toast(errorMessage)
          }else{
              Toast.fail('注册失败')
          }
          resolve();
        });
       });
       } finally {
    }
      isRegistering.value=false;
     }, 1000);
  } 
};


const clickRight =()=>{
    router.push('/login')
}
</script>

<style lang="scss" scoped>
  .slide-enter-active,
  .slide-leave-active {
    transition: transform 0.5s;
  }
  
  .slide-enter {
    transform: translateX(100%);
  }
  
  .slide-leave-to {
    transform: translateX(-100%);
  }
@import '@/styles/register.scss';
</style>
